package com.jinyi.wwdeng.ui.main.fragment

import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import android.view.animation.Animation
import android.view.animation.RotateAnimation
import androidx.core.content.ContextCompat
import androidx.core.view.GravityCompat
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.jinyi.base.utils.BarUtils
import com.jinyi.lib_baseadapter.BGAOnItemChildClickListener
import com.jinyi.wwdeng.App
import com.jinyi.wwdeng.AppConfigs
import com.jinyi.wwdeng.R
import com.jinyi.wwdeng.databinding.FragmentCreditAuditBinding
import com.jinyi.wwdeng.pro.ProMvpFragment
import com.jinyi.wwdeng.status.StatusRepository
import com.jinyi.wwdeng.ui.main.adapter.CreditAuditAppsAdapter
import com.jinyi.wwdeng.ui.main.contract.CreditAuditContract
import com.jinyi.wwdeng.ui.main.impl.CreditAuditPresenterImpl
import com.jinyi.wwdeng.ui.user.act.UserFeedbackAct
import com.jinyi.wwdeng.ui.user.fragment.UserFragment
import com.jinyi.wwdeng.utils.dialog.StarDialogContract
import com.jinyi.wwdeng.utils.event.TrackEventType
import com.jinyi.wwdeng.utils.event.TrackEventUtils
import com.jinyi.wwdeng.utils.recyclerview.LinearSpacingItemDecoration
import org.json.JSONObject

/**
 * JinYiTest
 * @Author wwdeng
 * @CreateTime: 2024/4/24 14:01
 * @Annotation：贷款审核中、放款中
 */
class CreditAuditFragment(val obj: JSONObject): ProMvpFragment<CreditAuditContract.View, CreditAuditPresenterImpl>(), CreditAuditContract.View  {

    lateinit var binding: FragmentCreditAuditBinding
    //推荐APP列表
    var mAppAdapter: CreditAuditAppsAdapter? = null

    override fun getRootView(inflater: LayoutInflater): View {
        binding = FragmentCreditAuditBinding.inflate(inflater)
        return binding.root
    }

    override fun createPresenter(): CreditAuditPresenterImpl {
        return CreditAuditPresenterImpl()
    }

    override fun initView() {
        binding.parentLayout.setPadding(0, BarUtils.getStatusBarHeight(),0,0)
        binding.tvTitle.text = getString(R.string.app_name)

        //添加侧边个人中心
        addMenuFragment()

        initRefreshLayout()
        initRecyclerViewApps()

        //订单状态
        val orderStatus = obj.optString("orderStatus")
        //放款中
        if (StatusRepository(null,orderStatus).isDisbursing()){
            binding.tipsLayout.setBackgroundResource(R.drawable.base_radius_frame_b2f0de_10)
            binding.ivAuditIcon.setImageResource(R.mipmap.pic_credit_success_icon)
            binding.tvAuditTips.text = getString(R.string.your_loan_application_has_been_approved)
            binding.tvAuditTips.setTextColor(ContextCompat.getColor(requireContext(),R.color.color_00ce90))
            binding.tvAuditTipsMsg.text = getString(R.string.the_loan_will_be_transferred_to_your_account)
            binding.ivRefreshStep.visibility = View.GONE
            return
        }

        //申请状态
        val applyStatus = obj.optString("applyStatus")
        //审核中
        if (StatusRepository(applyStatus).isReviewing()){
            binding.tipsLayout.setBackgroundResource(R.drawable.base_radius_frame_cbe1fd_10)
            binding.ivAuditIcon.setImageResource(R.mipmap.pic_credit_audit_tips_icon)
            binding.tvAuditTips.text = getString(R.string.your_loan_application_is_under_review)
            binding.tvAuditTips.setTextColor(ContextCompat.getColor(requireContext(),R.color.color_2e86f6))
            binding.tvAuditTipsMsg.text = getString(R.string.it_may_take_a_few_minutes)
            binding.ivRefreshStep.visibility = View.VISIBLE
        }

        //默认不显示 repayImportantLayout 和 transferDelayImportantLayout
        binding.repayImportantLayout.visibility = View.GONE
        binding.transferDelayImportantLayout.visibility = View.GONE
    }

    override fun initListener() {
        //个人中心
        binding.ivAvatar.setOnClickListener {
            var isOpen = binding.drawerLayout.isDrawerOpen(GravityCompat.START)
            if (isOpen){//是否打开
                binding.drawerLayout.closeDrawer(GravityCompat.START,true)
                TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_USER,"CreditAudit Page Close")
            } else {
                binding.drawerLayout.openDrawer(GravityCompat.START,true)
                TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_USER,"CreditAudit Page Open")
            }
        }
        //客服
        binding.ivKefu.setOnClickListener {
            onIntent(UserFeedbackAct::class.java)
            TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_CUSTOMER,"CreditAudit Page")
        }
        //刷新流程步骤
        binding.ivRefreshStep.setOnClickListener {
            //发送刷新流程广播
            val intent = Intent(AppConfigs.Action.ACTION_PROCESS_UPDATE)
            requireContext().sendBroadcast(intent)
            startRefresh()
            TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_CREDIT_AUDIT_REFRESH_PROCESS,"CreditAudit Page")
        }
    }

    override fun initData() {
        showLoading("")
        presenter.loadCreditLimitInfoRequest()
        presenter.loadScoreCommentAction()

        //从配置里判断是否有 repayImportant
        val commonData = JSONObject(AppConfigs.getSPString(AppConfigs.SP_KEY.SP_HENECREDIT_COMMON))
        val customize = commonData.optJSONObject("customize")
        if (customize != null){
            val repayImportant = customize.optString("repayImportant","")
            if (repayImportant.isNotEmpty()){
                binding.repayImportantLayout.visibility = View.VISIBLE
                binding.tvPepayImportant.text = repayImportant
            }

            val transferDelayImportant = customize.optString("transferDelayImportant","")
            if (transferDelayImportant.isNotEmpty()){
                binding.transferDelayImportantLayout.visibility = View.VISIBLE
                binding.tvTransferDelayImportant.text = transferDelayImportant
            }
        }
    }

    /* 初始化刷新 */
    private fun initRefreshLayout() {
        //禁止加载
        binding.refreshLayout.setEnableLoadMore(false)
        binding.refreshLayout.setEnableAutoLoadMore(false)
        binding.refreshLayout.setOnRefreshListener {
            val intent = Intent(AppConfigs.Action.ACTION_PROCESS_UPDATE)
            requireContext().sendBroadcast(intent)
            presenter.loadCreditLimitInfoRequest()
        }
        binding.refreshLayout.setOnLoadMoreListener {
            binding.refreshLayout.finishLoadMore()
        }
    }

    /**
     * 初始化可安装App列表
     */
    private fun initRecyclerViewApps(){
        binding.emptyLayout.emptyLayout.visibility = View.GONE
        binding.rvApps.layoutManager = LinearLayoutManager(context)
        val topDecoration = App.dp2px(12f)
        binding.rvApps.addItemDecoration(LinearSpacingItemDecoration(0,0,topDecoration,topDecoration))
        mAppAdapter = CreditAuditAppsAdapter(binding.rvApps)
        binding.rvApps.adapter = mAppAdapter!!
        binding.rvApps.itemAnimator = DefaultItemAnimator()
        mAppAdapter!!.setOnItemChildClickListener(BGAOnItemChildClickListener { _, childView, position ->
            val item = mAppAdapter!!.getItem(position)
            if (childView.id == R.id.btnInstall) {//切换item
                TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_CREDIT_AUDIT_RECOMMEND_APP_INSTALL,item.optString("appName"))
                val appLink = item.optString("appLink")
                if (appLink.isNotEmpty()){
                    val uri = Uri.parse(item.optString("appLink"))
                    val intent = Intent(Intent.ACTION_VIEW, uri)
                    startActivity(intent)
                }
            }
        })
    }

    /**
     * 添加侧边菜单
     */
    private fun addMenuFragment(){
        childFragmentManager
            .beginTransaction()
            .add(R.id.menuLayout, UserFragment(binding.drawerLayout)) // 此处的R.id.fragment_container是要盛放fragment的父容器
            .commitAllowingStateLoss()
    }

    /**
     * 刷新
     */
    private fun startRefresh(){
        // 设置旋转动画的参数：从当前角度旋转到720度，持续时间为500毫秒
        val rotateAnimation = RotateAnimation(0f, 1080f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f)
        rotateAnimation.setDuration(3000) // 设置动画持续时间
        rotateAnimation.fillAfter = true // 动画执行完后，View保持结束状态
        rotateAnimation.repeatCount = 0 //重复的次数，默认为0，必须是int，可以为-1表示不停止
        rotateAnimation.repeatMode = Animation.INFINITE //重复的模式
        // 启动动画
        binding.ivRefreshStep.startAnimation(rotateAnimation)
    }

    /**
     * 设置贷款信息
     */
    @SuppressLint("SetTextI18n")
    override fun showCreditLimitInfoData(data: JSONObject) {
        binding.tvAmount.text = data.optString("currency") + " " + data.optString("amount")
        binding.tvDays.text = data.optString("days") + getString(R.string.days)
        binding.tvUserAccount.text = "+" + data.optString("bankAccount")
    }

    /**
     * 设置推荐安装的App列表
     */
    override fun showRecommendAppList(appList: ArrayList<JSONObject>) {
        if (appList.size == 0){
            binding.rvApps.visibility = View.GONE
            binding.emptyLayout.emptyLayout.visibility = View.VISIBLE
            return
        }
        binding.rvApps.visibility = View.VISIBLE
        binding.emptyLayout.emptyLayout.visibility = View.GONE
        mAppAdapter!!.data = appList
    }

    /**
     * 展示评分配置弹框
     */
    override fun showScoreCommentData(data: JSONObject) {
        StarDialogContract.showScoreDialog(requireContext(),data,true)
    }

    /**
     * 已绑定账户列表（法语）
     */
    override fun setBindAccountList(accountList: ArrayList<JSONObject>) {
    }

    /**
     * 设置绑定其它账户（法语）
     */
    override fun showBingAccountOtherDialog(otherInfo: JSONObject?) {
    }

    override fun onRequestFinish() {
        super.onRequestFinish()
        hideLoading()
        binding.refreshLayout.finishRefresh()
    }

    override fun onStart() {
        super.onStart()
        TrackEventUtils.logEvent(TrackEventType.PAGE.PAGE_CREDIT_AUDIT_START,"")
    }

    override fun onDestroy() {
        super.onDestroy()
        TrackEventUtils.logEvent(TrackEventType.PAGE.PAGE_CREDIT_AUDIT_END,"")
    }
}